<?php

namespace App\Home\Models;

use App\Home\Traits\ModelHelpers;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;

class User extends Authenticatable
{
    use SoftDeletes;
    use Notifiable;
    use ModelHelpers;

    protected $guarded = []; 

    protected $hidden = ['password']; 

    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
		'updated_at' => 'datetime:Y-m-d H:i:s',
    ]; 

    /**
     * 从请求数据中添加用户
     *
     * @param array $inputs
     * @param bool $hashedPassword 传入的密码, 是否是没有哈希处理的明文密码
     *
     * @return AdminUser|\Illuminate\Database\Eloquent\Model
     */
    public static function createUser($inputs, $hashedPassword = false)
    {
        if (!$hashedPassword) {
            $inputs['password'] = bcrypt($inputs['password']);
        }

        return static::create($inputs);
    }

    /**
     * 从请求数据中查找用户
     *
     * @param array $inputs
     *
     * @return AdminUser|\Illuminate\Database\Eloquent\Model
     */
    public static function findUser($inputs)
    {
        return static::where($inputs)->first();
    }

    /**
     * 从请求数据中, 更新一条记录
     *
     * @param array $inputs
     * @param bool $hashedPassword 传入的密码, 是否是没有哈希处理的明文密码
     *
     * @return bool
     */
    public function updateUser($inputs, $hashedPassword = false)
    {
        // 更新时, 填了密码, 且没有经过哈希处理
        if (
            isset($inputs['password']) &&
            !$hashedPassword
        ) {
            $inputs['password'] = md5(md5($inputs['password']));
        }

        return $this->update($inputs);
    }

    /**
     * 创建不重复的Token
     * @return bool|string
     */
    public static function makeToken()
    {
        $token = md5(uniqid());
        if (self::query()->where('api_token', $token)->first()) {
            return self::makeToken();
        }
        return $token;
    }
}
